package com.glory.brepda.activity.mfg;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.MantissaLotListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.CarrierListEntity;
import com.glory.brepda.entity.LotList;
import com.glory.brepda.entity.SimpleEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FTTrackOutBiandaiSuccess3Activity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.rvReelLotList)
    RecyclerView rvReelLotList;
    @BindView(R.id.etReelNum)
    TextView etReelNum;
    @BindView(R.id.tvCreateReel)
    TextView tvCreateReel;
    @BindView(R.id.rvTrackOutList)
    RecyclerView rvTrackOutList;
    @BindView(R.id.cbTrackOut)
    CheckBox cbTrackOut;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etMaterielModel)
    EditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.llBoxLayout)
    LinearLayout llBoxLayout;
    private String mLotID;
    private String mReelNum;
    private String mBinName;
    private String mEqpid;
    private MantissaLotListAdapter mMantissaLotListAdapter;
    private MantissaLotListAdapter mMantissaLotListAdapter2;
    private SimpleEntity.MantissaLotBinData mData;
    private AddCarrierDataAdapter materielModeAdapter;
    private String SHOWMSG = "Y";
    private List<LotList> mLotList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_fttrack_out_biandai_success3;
    }

    @Override
    protected void initView() {
        llBoxLayout.setVisibility(View.GONE);
        setMainLayout(llMain);
        tvTitle.setText("正常结束-(编带出站)");
        Bundle bundle = getIntent().getExtras();
        setMainLayout(llMain);
        mLotID = bundle.getString("LOTID");
        mReelNum = bundle.getString("REELNUM");
        mBinName = bundle.getString("BINNAME");
        mEqpid = bundle.getString("EQPID", "");
        String mManTissaFlag = bundle.getString("MANTISSAFLAG");
        cbTrackOut.setChecked(mManTissaFlag.equals("Y"));
        mLotList.add(new LotList(mLotID));
        mData = (SimpleEntity.MantissaLotBinData) bundle.getSerializable("SELECTORDATA");
        etReelNum.setText(mReelNum);
        initRecyclerView(rvReelLotList,this);
        mMantissaLotListAdapter = new MantissaLotListAdapter(null,true);
        mMantissaLotListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mMantissaLotListAdapter.isFirstOnly(true);
        rvReelLotList.setAdapter(mMantissaLotListAdapter);
        mMantissaLotListAdapter.addData(mData);
        initRecyclerView(rvTrackOutList,this);
        mMantissaLotListAdapter2 = new MantissaLotListAdapter(null,true);
        mMantissaLotListAdapter2.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mMantissaLotListAdapter2.isFirstOnly(true);
        rvTrackOutList.setAdapter(mMantissaLotListAdapter2);
        initRecyclerView(rvMaterielModelList,this);
        materielModeAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModeAdapter);
        addActivity(this);

        initEdit(etMaterielModel, s -> {
            if (materielModeAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            materielModeAdapter.getData().add(s);
            materielModeAdapter.notifyDataSetChanged();
            etMaterielModel.setText("");
        });
    }

    @Override
    protected void initData() {
        requestData("SelectBinData");
    }

    private void requestData(String actionType) {
        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (!entity.getTRACKSHOWMSG().equals("")){
                        FreeApi_DialogUtils.getConfirmDialog(FTTrackOutBiandaiSuccess3Activity.this, "確定",
                                entity.getTRACKSHOWMSG(), () -> {
                                    fillData(actionType,response.body().getResponse().getBody());
                                }).show(getSupportFragmentManager(),"MSG_DIALOG");
                    }else {
                        fillData(actionType,response.body().getResponse().getBody());
                    }


                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", actionType);
        map.addProperty("EQUIPMENTID", mEqpid);
        map.addProperty("MANTISSAFLAG", cbTrackOut.isChecked() ? "Y" : "N");
        map.addProperty("REELNUM", mReelNum);
        map.addProperty("PACKAGETYPE", "REEL");
        map.addProperty("SHOWMSG", SHOWMSG);
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(mLotList)).getAsJsonArray());
        map.add("LOTBINDATALIST", new JsonParser().parse(new Gson().toJson(mMantissaLotListAdapter.getData())).getAsJsonArray());
        if (actionType.equals("NomalTrackout")){
            List<CarrierListEntity> carrierList = new ArrayList<>();
            if (materielModeAdapter.getData().size() > 0){
                for (String s : materielModeAdapter.getData()){
                    carrierList.add(new CarrierListEntity(s));
                }
            }
            map.add("LOTMULTICARRIERLIST", new JsonParser().parse(new Gson().toJson(carrierList)).getAsJsonArray());
        }
        NetUtils.requestPostNet("IF.LOTFTTRACKOUT", "LOTFTTRACKOUT", FTTrackOutBiandaiSuccess3Activity.this, map, callBack);
    }

    private void fillData(String actionType,SimpleEntity entity) {
        if (actionType.equals("SelectBinData")){
            for (SimpleEntity.MantissaLotBinData data : entity.getMANTISSALOTBINDATALIST()){
                if (data.getBINNAME().equals(mBinName)){
                    mLotList.add(new LotList(data.getLOTID()));
                    mMantissaLotListAdapter.addData(data);
                }
            }

            return;
        }

        if (SHOWMSG.equals("Y")){
            showSubmitDialog(() -> {
                SHOWMSG = "N";
                requestData("NomalTrackout");
            },entity.getTRACKSHOWMSG());
        }else {
            requestTrackOutByEqpId(entity);
        }
    }

    //eap单独增加接口
    private void requestTrackOutByEqpId(SimpleEntity entity) {
        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                //不论当前接口成功或失败，都要提示出站成功
                showConfirmDialogFinishAll("出站成功,批次：" + entity.getLOTLIST().get(0).getLOTID());
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"CPC.TrackOutByEqpId");
                showConfirmDialogFinishAll("出站成功,批次：" + entity.getLOTLIST().get(0).getLOTID());
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",mEqpid);
        NetUtils.requestPostNet("IF.TrackOutByEqpId","TrackOutByEqpId",FTTrackOutBiandaiSuccess3Activity.this,map,callBack);
    }

    @OnClick({R.id.tvBaseSubmit, R.id.cbTrackOut})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (mReelNum.equals("0")){
                    showToast("卷盘包装数量为0",false);
                    return;
                }

                if (calculation() < Integer.parseInt(mReelNum)){
                    showToast("数量不能小于卷盘包装数量",false);
                    return;
                }

                if (materielModeAdapter.getData().size() <= 0){
                    FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "当前未绑定载具是否继续提交?", ()
                            -> requestData("NomalTrackout"), () -> {}).show(getSupportFragmentManager(),"NOT_CARRIER");
                    return;
                }
                //出站Dialog
                showSubmitDialog(() -> requestData("NomalTrackout"));
                break;
            case R.id.cbTrackOut:
                break;
        }
    }

    private int calculation() {
        int sum = 0;
        for (SimpleEntity.MantissaLotBinData data : mMantissaLotListAdapter.getData()){
            sum +=  data.getMAINQTY();
        }
        return sum;
    }
}
